package cc.rengu.igas.channel.cups.core.packswitch;

import cc.rengu.jradp.service.communication.CupsChannelProxyImpl;
import cc.rengu.utility.log.RgLog;
import cc.rengu.utility.log.RgLogger;

/**
 * @author who
 */
public class CupsProxyGetRadpKey implements CupsChannelProxyImpl {
    private static final int EVEN = 2;

    @Override
    public int getPacketType(byte[] arg0) {
        // 从8583消息类型第三位判断是CUPS的应答还是请求
        RgLogger rglog = RgLog.getLogger("CupsproxyGetRadpKey");

        byte[] mti = new byte[4];
        System.arraycopy(arg0, 46, mti, 0, 4);
        int flag = mti[2] - '0';
        if (0 == flag % EVEN) {
            //CUPS请求
            rglog.info("CUPS请求交易");
            rglog.printHex(arg0);
            return CupsChannelProxyImpl.Type_Request;
        } else {
            //CUPS应答
            rglog.info("CUPS应答交易");
            rglog.printHex(arg0);
            return CupsChannelProxyImpl.Type_Response;
        }

    }

    @Override
    public int getSourceId(byte[] arg0) {
        //报文头field9 用户信息 一个字节，取值1-255表示连接的客户端编号
        RgLogger rglog = RgLog.getLogger("CupsproxyGetRadpKey");
        rglog.info("获取到的信息为");
        rglog.printHex(arg0);

//		@SuppressWarnings("unused")
        byte[] userInformation = new byte[1];
        //目前仿真不原样field9 用户信息，先写死；规范上规定是要原样返回的,扩展到1-255
        System.arraycopy(arg0, 40, userInformation, 0, 1);
        int id = userInformation[0];
//		int id = 1;
        rglog.info("原信息的来源id为={}", id);
        if (id >= 0) {
            return id;
        } else {
            return -1;
        }

    }

    @Override
    public byte[] markSourceId(byte[] arg0, int arg1) {
        //报文头field9 用户信息 一个字节，取值0-255表示连接的客户端编号
        RgLogger rglog = RgLog.getLogger("CupsproxyGetRadpKey");
//		rglog.info("标记来源id={}前报文",arg1);
//		rglog.printHex(arg0);
        byte[] userInformation = new byte[1];
//		rglog.debug("报文头field9 用户信息[{}]", new String(userInformation));		
        userInformation[0] = Integer.valueOf(arg1).byteValue();
        System.arraycopy(userInformation, 0, arg0, 40, 1);
        rglog.info("标记来源id={}后报文", arg1);
        rglog.printHex(arg0);
        return arg0;
    }
}
